<?php
//require_once APPPATH.'third_party/wxmsgcrypt/wxBizMsgCrypt.php';
class Wxcallbackapi
{
	private $_appid;
	private $_appsecret;
	private $_wx_type;
	private $CI;
	private $_token;
	private $_nonce;
	private $_timestamp;
	private $_signature;
	private $_redis;
	//加密模式
    /*private $_crypt;
	private $_msg_signature;
	private $_aeskey;*/

	public function __construct($config = array())
    {
        $this->CI = &get_instance();
        if (!empty($config)){
            $this->_appid = $config['appid'];
            $this->_appsecret = $config['appsecret'];
            $this->_wx_type = $config['wxtype'];
            $this->_token = $config['token'];
            $this->_aeskey = $config["aeskey"];

            $this->_nonce = $_GET["nonce"];
            $this->_timestamp = $_GET["timestamp"];
            $this->_signature = $_GET["signature"];
            //加密模式
//            $this->_msg_signature = $_GET["msg_signature"];
        } else {
            echo 'lack appid and appsecret';exit();
        }
    }

    //验证消息
	public function valid()
	{
		$echoStr = $_GET["echostr"];
		if($this->checkSignature()){
			echo $echoStr;
			exit;
		}
	}

	//检查签名
	private function checkSignature()
	{
	    $tmpArr = array($this->_token, $this->_timestamp, $this->_nonce);
		sort($tmpArr, SORT_STRING);
		$tmpStr = implode($tmpArr);
		$tmpStr = sha1($tmpStr);

		if($tmpStr == $this->_signature){
			return true;
		}else{
			return false;
		}
	}

	//响应消息
	public function responseMsg()
	{
		$postStr = $GLOBALS["HTTP_RAW_POST_DATA"];
//        $this->_crypt = new WXBizMsgCrypt($this->_token,$this->_aeskey,$this->_appid);
		if (!empty($postStr)){
//            $msg = '';
//		    $rescode = $this->_crypt->decryptMsg($this->_msg_signature,$this->_timestamp,$this->_nonce,$postStr,$msg);
//		    if ($rescode === 0){
            //解密成功业务代码
//            }else{
//		        log_message('error',$rescode);
//		        return "";
//            }
            //解析xml
            $postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
            $jsonStr = json_encode($postObj);
            $jsonArr = json_decode($jsonStr,true);
            $RX_TYPE = trim($jsonArr['MsgType']);

            switch ($RX_TYPE)
            {
                case "event":
                    $result = $this->receiveEvent($jsonArr);
                    break;
                case "text":
                    $result = $this->receiveText($jsonArr);
                    break;
                case "image":
                    $result = $this->receiveImage($jsonArr);
                    break;
                case "video":
                    $result = $this->receiveVideo($jsonArr);
                    break;
                case "shortvideo":
                    $result = $this->receiveVideo($jsonArr);
                    break;
                case "voice":
                    $result = $this->receiveVoice($jsonArr);
                    break;
                case "location":
                    $result= $this->receiveLocation($jsonArr);
                    break;
                case "link":
                    $result= $this->receiveLink($jsonArr);
                    break;
                default:
                    $result="";
                    break;

            }
            return $result;
		}else {
			return  "";
		}
	}
	private function receiveImage($object)
	{
		$content="这张照片真漂亮！";
		$result=$this->transmitText($object, $content);
		return $result;
	}

	private function receiveVideo($object)
	{
		$content="这个视频看上去好像挺有趣的！";
		$result=$this->transmitText($object, $content);
		return $result;
	}

	//接收事件消息
	private function receiveEvent($object)
	{
	    $result = "";
		switch ($object['Event'])
		{
			case "subscribe":
			    $result=$this->replySubEvent($object);
				break;
            case "SCAN":
                $result=$this->replyScanEvent($object);
                break;
		}

		return $result;
	}
	public function replySubEvent($object)
    {
        $result = "";
        switch ($this->_wx_type){
            case 'nldou_fuwu':
            case 'test':
                if (isset($object['EventKey'])&&!empty($object['EventKey'])){
                    //扫描带参数二维码关注公号
                    $result=$this->replyKeySubEvent($object);
                }else{
                    //普通关注公号
                    $result=$this->replyNokeySubEvent($object);
                }
                break;
        }
        return $result;
    }
    public function replyNokeySubEvent($object)
    {
        $touser = $object['FromUserName'];
        $tousername = $this->getUserNickName($touser);
        $content="Hi，".$tousername."，终于等到您啦！感谢您关注“能量逗”微信公众号哦！么么哒~\n\n".
            "了解更多卡牌信息，获得卡牌教程视频，请戳-->\n".
            "http://wap.nldou.com/hardfun\n".
            "或点底部菜单栏能量空间->卡牌视频教程\n\n".
            "~逗，你玩儿？\n".
            "如需收看单套卡牌游戏说明视频，请直接回复卡牌名称。如：土豆快跑，即可获取\n\n".
            "让孩子玩转学习力，让家庭充满欢乐，能量逗你值得拥有！";
        //回复
        $result=$this->transmitText($object,$content);
        return $result;
    }
    public function replyKeySubEvent($object)
    {
        //扫描参数二维码并关注
        $eventkey = substr($object['EventKey'],8);/*去掉前缀qrscene_*/
        $eventkeyarr = explode('.',$eventkey);
        $sceneid = (int)$eventkeyarr[0];
        //统计
        $this->saveKeySubEventStat($sceneid,$eventkeyarr,$object);
        $result = $this->keyEventHandler($sceneid,$object,$eventkeyarr);
        return $result;
    }
    public function saveKeySubEventStat($sceneid,$data,$object)
    {
        $statdata = array(
            "wx_type"=>$this->_wx_type,
            "sceneid"=>$sceneid,
            "timestamp"=>time(),
            "openid"=>$object['FromUserName'],
            "info"=>array()
        );
        switch ($sceneid){
            case 3001:
                $statdata['info']['sls'] = $data[1];
                $statdata['info']['postid'] = $data[2];
                break;
            case 3002:
                $statdata['info']['sls'] = $data[1];
                $statdata['info']['postid'] = $data[2];
                break;
        }

        if (!isset($this->_redis)){
            $this->CI->load->model('redis_model');
            $this->_redis=$this->CI->redis_model->getRedisInstance();
        }

        $statdata = json_encode($statdata);
        $this->_redis->rPush($this->_wx_type.'.qrscansub.stat',$statdata);
    }
    public function replyScanEvent($object)
    {
        $result = "";
        switch ($this->_wx_type){
            case 'nldou_fuwu':
            case 'test':
                if (isset($object['EventKey'])) {
                    $result=$this->replyKeyScanEvent($object);
                }
                break;
        }
        return $result;
    }
    public function replyKeyScanEvent($object)
    {
        $eventkeyarr = explode('.',$object['EventKey']);
        $sceneid = (int)$eventkeyarr[0];
        $result = $this->keyEventHandler($sceneid,$object,$eventkeyarr);
        return $result;
    }
    public function keyEventHandler($sceneid,$object,$eventkeyarr)
    {
        $touser = $object['FromUserName'];
        $result = "";
        switch ($sceneid){
            //扫描代言人二维码关注公号
            case 3001:
                $tousername = $this->getUserNickName($touser);
                //关注语
                $content="Hi，".$tousername."，终于等到您啦！感谢您关注“能量逗”微信公众号哦！么么哒~\n\n".
                    "了解更多卡牌信息，获得卡牌教程视频，请戳-->\n".
                    "http://wap.nldou.com/hardfun\n".
                    "或点底部菜单栏能量空间->卡牌视频教程\n\n".
                    "~逗，你玩儿？\n".
                    "如需收看单套卡牌游戏说明视频，请直接回复卡牌名称。如：土豆快跑，即可获取\n\n".
                    "让孩子玩转学习力，让家庭充满欢乐，能量逗你值得拥有！";
                //回复
                $result=$this->transmitText($object,$content);
                break;
            case 3002:
                $tousername = $this->getUserNickName($touser);
                //商品链接
                $custommsgdata=array("touser"=>$touser,"msgtype"=>"text",
                    "text"=>array("content"=>"亲爱的".$tousername."，您的朋友给您推荐了能量逗益智桌游，赶紧戳下方链接看看吧！"));
                $this->transmitCustomMsg($custommsgdata);
                $articledata=array(
                    array(
                        "Title"=>"能量逗商城，点击进入",
                        "Description"=>"",
                        "url"=>"https://h5.youzan.com/v2/trade/directsellerJump/jump?kdt_id=18168297&sl=".$eventkeyarr[1].
                            "&redirect_uri=".urlencode("https://h5.youzan.com/v2/showcase/homepage?kdt_id=18168297&sls=".$eventkeyarr[1]),
                        "PicUrl"=>"http://wap.nldou.com/upload/images/20180411/81ae5a080f1d860f9e4252506b8bb652.jpg"
                    )
                );
                $result=$this->transmitArticles($object,$articledata);
                break;
        }
        return $result;
    }

	//接收文本消息
	private function receiveText($object)
	{
		$result = $this->autoreply($object);
		return $result;
	}

	private function autoreply($object)
    {
        $rule = $this->getAutoreplyContent($object['Content']);
        $res = '';
        //有匹配时
        if ($rule!==false){
            switch ($rule['reply']['type']){
                case 'article':
                    $res = $this->transmitArticles($object,$rule['reply']['info']['articles']);
                    break;
            }
        }
        return $res;
    }

	private function getAutoreplyContent($content)
    {
        $rules = array(
            array(
                "keywords"=>array("土豆","快跑"),
                "reply"=>array(
                    "type"=>"article",
                    "info"=>array(
                        "articles"=>array(
                            array(
                                "Title"=>"土豆快跑游戏说明",
                                "Description"=>"",
                                "PicUrl"=>"http://mmbiz.qpic.cn/mmbiz_jpg/LZ3SBrr6vjCEJWJ8apXQ8bVzDFKNrPbfhzyERoSDMDhPKjS3z74dOibG1QFl9tXeGU3PUtXdibiaZDtd9qQfhCdrg/0?wx_fmt=jpeg",
                                "url"=>"http://mp.weixin.qq.com/s?__biz=MzA3MTQ5ODAxNA==&mid=502393147&idx=1&sn=34d013174ab214cf7932ec077529132b&chksm=0729e94a305e605c5872b7105013b0c3bd563bedcae7e6b528c8ced1c79c93ced20407810819#rd"
                            )
                        )
                    )
                )
            ),
            array(
                "keywords"=>array("彩虹","乐园"),
                "reply"=>array(
                    "type"=>"article",
                    "info"=>array(
                        "articles"=>array(
                            array(
                                "Title"=>"彩虹乐园游戏说明",
                                "Description"=>"",
                                "PicUrl"=>"http://mmbiz.qpic.cn/mmbiz_jpg/LZ3SBrr6vjCEJWJ8apXQ8bVzDFKNrPbffJPD00zibX0TtygPrzRqTDM3h8wGzWde2Hib9GS8qz2jDM8ff1kSvIPQ/0?wx_fmt=jpeg",
                                "url"=>"http://mp.weixin.qq.com/s?__biz=MzA3MTQ5ODAxNA==&mid=502393139&idx=1&sn=6b2419c2a37cc69b8400588caf5bc494&chksm=0729e942305e6054e64523c9971d674f4e88f0a530116bc5fa042f4741376d9a0a03eb989ff1#rd"
                            )
                        )
                    )
                )
            ),
            array(
                "keywords"=>array("逗逗","豆豆","分队"),
                "reply"=>array(
                    "type"=>"article",
                    "info"=>array(
                        "articles"=>array(
                            array(
                                "Title"=>"逗逗小分队游戏说明",
                                "Description"=>"",
                                "PicUrl"=>"http://mmbiz.qpic.cn/mmbiz_jpg/LZ3SBrr6vjCEJWJ8apXQ8bVzDFKNrPbfiaqhQic7kWvrLlUMgyCbGp46lapDWpRJoziaZ6UW2dzcV9ljMGdiboKVTQ/0?wx_fmt=jpeg",
                                "url"=>"http://mp.weixin.qq.com/s?__biz=MzA3MTQ5ODAxNA==&mid=502393161&idx=1&sn=15c676c9037e1d875f5024bb6f0f0ac5&chksm=0729e938305e602ed5b1a7d9808161f728c7a75d503489ef4304b0cc3d420ab8f2e95a3c96c0#rd"
                            )
                        )
                    )
                )
            ),
            array(
                "keywords"=>array("加","10","十","时"),
                "reply"=>array(
                    "type"=>"article",
                    "info"=>array(
                        "articles"=>array(
                            array(
                                "Title"=>"加10赛游戏说明",
                                "Description"=>"",
                                "PicUrl"=>"http://mmbiz.qpic.cn/mmbiz_jpg/LZ3SBrr6vjCEJWJ8apXQ8bVzDFKNrPbfeX40HMfErNuuyBiaVblHR3KHUpXOb5H3foUI7TeqJVCu3HdicHicpHjYg/0?wx_fmt=jpeg",
                                "url"=>"http://mp.weixin.qq.com/s?__biz=MzA3MTQ5ODAxNA==&mid=502393137&idx=1&sn=441334c0ff0539db86a6001644302a3a&chksm=0729e940305e6056a5a8f2f414522bc280d9b4a273655a943c735a5db570fc8d985679da3245#rd"
                            )
                        )
                    )
                )
            ),
            array(
                "keywords"=>array("小鸭","农场","嘎嘎"),
                "reply"=>array(
                    "type"=>"article",
                    "info"=>array(
                        "articles"=>array(
                            array(
                                "Title"=>"小鸭农场游戏说明",
                                "Description"=>"",
                                "PicUrl"=>"http://mmbiz.qpic.cn/mmbiz_jpg/LZ3SBrr6vjCEJWJ8apXQ8bVzDFKNrPbf89lMwYl9l9hj9kztiadiaYrsu2BHt4k9CEzGcIxb2jxhledB2j3WNFxQ/0?wx_fmt=jpeg",
                                "url"=>"http://mp.weixin.qq.com/s?__biz=MzA3MTQ5ODAxNA==&mid=502393149&idx=1&sn=55c5beff7858cac463b7f3141c148fb0&chksm=0729e94c305e605adcf1576be61e54b50bac04972a874c5f03719a6f057e09f2f08dd9f45561#rd"
                            )
                        )
                    )
                )
            ),
            array(
                "keywords"=>array("小兔","一家","乖乖"),
                "reply"=>array(
                    "type"=>"article",
                    "info"=>array(
                        "articles"=>array(
                            array(
                                "Title"=>"小兔一家亲游戏说明",
                                "Description"=>"",
                                "PicUrl"=>"http://mmbiz.qpic.cn/mmbiz_jpg/LZ3SBrr6vjCEJWJ8apXQ8bVzDFKNrPbf2IxQK2Zqlmd2ZC4dpGPOhuKJnMIlJib8cxXz7t5ZKJicBibNYk4o6sYSQ/0?wx_fmt=jpeg",
                                "url"=>"http://mp.weixin.qq.com/s?__biz=MzA3MTQ5ODAxNA==&mid=502393159&idx=1&sn=b28cbee122bd4314aa00ae2893d4b485&chksm=0729e936305e602028c1f8761f8380c3d5dc6a468820bd05901e402780d9038649936d8efb31#rd"
                            )
                        )
                    )
                )
            ),
            array(
                "keywords"=>array("GO","go","Go","gO","碰"),
                "reply"=>array(
                    "type"=>"article",
                    "info"=>array(
                        "articles"=>array(
                            array(
                                "Title"=>"GOGO碰游戏说明",
                                "Description"=>"",
                                "PicUrl"=>"http://mmbiz.qpic.cn/mmbiz_jpg/LZ3SBrr6vjCEJWJ8apXQ8bVzDFKNrPbfz3mgpgF4epTAoo4icOVcjA91g3eLVDO1mhMA7RgL1y6QibsicDmntGxIQ/0?wx_fmt=jpeg",
                                "url"=>"http://mp.weixin.qq.com/s?__biz=MzA3MTQ5ODAxNA==&mid=502393151&idx=1&sn=e82166622dc027daa0e9d05ea2d84351&chksm=0729e94e305e605835bbf1c6a3978caac579103a853251a5a0a04d78e49a58806dec693e99a9#rd"
                            )
                        )
                    )
                )
            ),
            array(
                "keywords"=>array("表情"),
                "reply"=>array(
                    "type"=>"article",
                    "info"=>array(
                        "articles"=>array(
                            array(
                                "Title"=>"表情帝游戏说明",
                                "Description"=>"",
                                "PicUrl"=>"http://mmbiz.qpic.cn/mmbiz_jpg/LZ3SBrr6vjCEJWJ8apXQ8bVzDFKNrPbfX3MUWLLWvNUrqefXZAcxuFBzSTRkIvxOInapjt6fc7Ovv46Wc3zIIg/0?wx_fmt=jpeg",
                                "url"=>"http://mp.weixin.qq.com/s?__biz=MzA3MTQ5ODAxNA==&mid=502393143&idx=1&sn=f4875cfb55298f08cd48b9a5f0e3b471&chksm=0729e946305e605059b4ea46fe0f2a7f4d27859677ca0c740b442cc31c85c1df28b31c803db2#rd"
                            )
                        )
                    )
                )
            ),
            array(
                "keywords"=>array("喵喵","猫猫","寻找"),
                "reply"=>array(
                    "type"=>"article",
                    "info"=>array(
                        "articles"=>array(
                            array(
                                "Title"=>"寻找喵喵游戏说明",
                                "Description"=>"",
                                "PicUrl"=>"http://mmbiz.qpic.cn/mmbiz_jpg/LZ3SBrr6vjCEJWJ8apXQ8bVzDFKNrPbfZ60pfXKkcSfLdZ2fYbZFYa4U43wm8NhPFu5dKPyeQuvO3WGyLTiaxkw/0?wx_fmt=jpeg",
                                "url"=>"http://mp.weixin.qq.com/s?__biz=MzA3MTQ5ODAxNA==&mid=502393145&idx=1&sn=d09db235b78efe26efdaf02c67e32eb4&chksm=0729e948305e605ee7cfb95ab34ce0f3c157b04af5b3ea2fb6bb193c04d0a84a417047636d57#rd"
                            )
                        )
                    )
                )
            ),
            array(
                "keywords"=>array("指环","王"),
                "reply"=>array(
                    "type"=>"article",
                    "info"=>array(
                        "articles"=>array(
                            array(
                                "Title"=>"指环王游戏说明",
                                "Description"=>"",
                                "PicUrl"=>"http://mmbiz.qpic.cn/mmbiz_jpg/LZ3SBrr6vjCEJWJ8apXQ8bVzDFKNrPbf6ddtAUAqa4yOCef2icJpzoL3SXlWcrCRmo50wkeVTZI2AgHj4iboib55Q/0?wx_fmt=jpeg",
                                "url"=>"http://mp.weixin.qq.com/s?__biz=MzA3MTQ5ODAxNA==&mid=502393154&idx=1&sn=1f10605ef875c75a460dd9172c16e4cb&chksm=0729e933305e6025e69b884396a9691e6cbab3184cc36608e0a858a0ee3c56897ec71aae2e2c#rd"
                            )
                        )
                    )
                )
            ),
            array(
                "keywords"=>array("图形","接龙"),
                "reply"=>array(
                    "type"=>"article",
                    "info"=>array(
                        "articles"=>array(
                            array(
                                "Title"=>"图形接龙游戏说明",
                                "Description"=>"",
                                "PicUrl"=>"http://mmbiz.qpic.cn/mmbiz_jpg/LZ3SBrr6vjCEJWJ8apXQ8bVzDFKNrPbfuLVfh1L8YzYL4aavRP6yrEibkPhAIcGqsicKNLCM7Bzd29iaprRo5G4zg/0?wx_fmt=jpeg",
                                "url"=>"http://mp.weixin.qq.com/s?__biz=MzA3MTQ5ODAxNA==&mid=502393141&idx=1&sn=172a479eb1d52ccf870fd3ea7eebfdcb&chksm=0729e944305e60521bf37619da478b18fc4b7a0c6c8ea392d5108b6a6527e8463100c41f33d1#rd"
                            )
                        )
                    )
                )
            ),
            array(
                "keywords"=>array("分类","连连"),
                "reply"=>array(
                    "type"=>"article",
                    "info"=>array(
                        "articles"=>array(
                            array(
                                "Title"=>"分类连连看游戏说明",
                                "Description"=>"",
                                "PicUrl"=>"http://mmbiz.qpic.cn/mmbiz_jpg/LZ3SBrr6vjCEJWJ8apXQ8bVzDFKNrPbfpcyTOvDz8Ge1IfL27Z98YLnYWx5xNRlhddibxuLXjicHEdzk5dJ0An4A/0?wx_fmt=jpeg",
                                "url"=>"http://mp.weixin.qq.com/s?__biz=MzA3MTQ5ODAxNA==&mid=502393156&idx=1&sn=20b50379c450cd972d027f895eba0bad&chksm=0729e935305e6023b710e30fc6139a92d68beed27100dfb4982087c86fce5db24745b0dfabc7#rd"
                            )
                        )
                    )
                )
            ),
            array(
                "keywords"=>array("股票","大亨"),
                "reply"=>array(
                    "type"=>"article",
                    "info"=>array(
                        "articles"=>array(
                            array(
                                "Title"=>"股票大亨游戏说明",
                                "Description"=>"",
                                "PicUrl"=>"http://mmbiz.qpic.cn/mmbiz_png/LZ3SBrr6vjC2tTdnQzDWHI8ZbBdPgFm2s5vQvowkNibViccPZmv3MlzGqTQcfHZPdktDA6hSCMqkefibk0t2fZnsQ/0?wx_fmt=png",
                                "url"=>"http://mp.weixin.qq.com/s?__biz=MzA3MTQ5ODAxNA==&mid=502393259&idx=1&sn=6bc42699733d17d687f380396d5da3cf&chksm=0729e9da305e60cc0ed5af3017309de02cc6dfe7739c4eed12c0a30b00fcf699e12b631710bb#rd"
                            )
                        )
                    )
                )
            ),
            array(
                "keywords"=>array("蘑菇"),
                "reply"=>array(
                    "type"=>"article",
                    "info"=>array(
                        "articles"=>array(
                            array(
                                "Title"=>"采蘑菇游戏说明",
                                "Description"=>"",
                                "PicUrl"=>"http://mmbiz.qpic.cn/mmbiz_png/LZ3SBrr6vjC2tTdnQzDWHI8ZbBdPgFm2UDO8NFhCgZDyEletqTkvbGan68crsZgiao1kwoHmzJLRvD3tzoMf7fg/0?wx_fmt=png",
                                "url"=>"http://mp.weixin.qq.com/s?__biz=MzA3MTQ5ODAxNA==&mid=502393257&idx=1&sn=a82f61f4dee280f5c04cea45387c2cd1&chksm=0729e9d8305e60ce6a5fab674cb1eb12c413456421fd2ab4ce7344d3f71e3455516919107fef#rd"
                            )
                        )
                    )
                )
            ),
            array(
                "keywords"=>array("古诗","你来我往"),
                "reply"=>array(
                    "type"=>"article",
                    "info"=>array(
                        "articles"=>array(
                            array(
                                "Title"=>"你来我往猜古诗游戏说明",
                                "Description"=>"",
                                "PicUrl"=>"http://mmbiz.qpic.cn/mmbiz_png/LZ3SBrr6vjC2tTdnQzDWHI8ZbBdPgFm2xLEH0Bttdiby5ChYoR9zKmibuYTcXRr2s5icHu7micQnZqkNict6Qvl1gQw/0?wx_fmt=png",
                                "url"=>"http://mp.weixin.qq.com/s?__biz=MzA3MTQ5ODAxNA==&mid=502393248&idx=1&sn=e0452beb2c3bb945ea0bd5c2d22c70a1&chksm=0729e9d1305e60c7f885d149071cbaf7ffe91042717b5e4f2893664f69d9b7efcb136ced760d#rd"
                            )
                        )
                    )
                )
            ),
            array(
                "keywords"=>array("小鼠","波波"),
                "reply"=>array(
                    "type"=>"article",
                    "info"=>array(
                        "articles"=>array(
                            array(
                                "Title"=>"小鼠波波游戏说明",
                                "Description"=>"",
                                "PicUrl"=>"http://mmbiz.qpic.cn/mmbiz_png/LZ3SBrr6vjCojoRInpxpev8ia8f2ib9LngA9JTTSGl8kujB0mytODzQ4yH35DeViaAwzEzE3OEUbmvfg560ibNdvbQ/0?wx_fmt=png",
                                "url"=>"http://mp.weixin.qq.com/s?__biz=MzA3MTQ5ODAxNA==&mid=502393119&idx=1&sn=96125b3b893c9f622c1e5139222da4f0&chksm=0729e96e305e60785ca058fcdfc89d34e1177edfbe60e75bac5636f3d323a69445a85ec3a7dc#rd"
                            )
                        )
                    )
                )
            )
        );
        foreach ($rules as $r){
            foreach ($r['keywords'] as $w){
                if (strpos($content,$w)!==false){
                    return $r;
                }
            }
        }
        return false;
    }
	
	private function receiveVoice($object){
		$result=$this->transmitService($object);
		return $result;
	}
	
	private function receiveLocation($object){
		$content="为什么发给我坐标呢？如果有什么需要，请点击菜单栏客服哦！";
		$result=$this->transmitText($object, $content);
		return $result;
	}
	
	private function receiveLink($object)
	{
		$content="为什么发给我链接呢？如果有什么需要，请点击菜单栏客服哦！";
		$result=$this->transmitText($object, $content);
		return $result;
	}
	//------------------------------------------------------------
//    private function encrypt($xml)
//    {
//        $encryptMsg = '';
//        $this->_crypt->encryptMsg($xml,$this->_timestamp,$this->_nonce,$encryptMsg);
//        log_message('error',$encryptMsg);
//        return $encryptMsg;
//    }

	private function transmitText($object, $content)
	{
		$xml = "<xml>
		<ToUserName><![CDATA[%s]]></ToUserName>
		<FromUserName><![CDATA[%s]]></FromUserName>
		<CreateTime>%s</CreateTime>
		<MsgType><![CDATA[text]]></MsgType>
		<Content><![CDATA[%s]]></Content>
		</xml>";
		$result = sprintf($xml, $object['FromUserName'], $object['ToUserName'], time(), $content);
		return $result;
	}

	private function transmitMusic($object, $musicarr)
	{
        $musicarr['ThumbMediaId'] = $this->getMediaid($musicarr['thumburl'],'thumb', $musicarr['thumbname']);
		$item = "<Music>
	    <Title><![CDATA[%s]]></Title>
	    <Description><![CDATA[%s]]></Description>
	    <MusicUrl><![CDATA[%s]]></MusicUrl>
	    <HQMusicUrl><![CDATA[%s]]></HQMusicUrl>
	    <ThumbMediaId><![CDATA[%s]]></ThumbMediaId>
		</Music>";

		$item_xml = sprintf($item, $musicarr['Title'], $musicarr['Description'], $musicarr['MusicUrl'], $musicarr['HQMusicUrl'], $musicarr['ThumbMediaId']);

		$xml = "<xml>
		<ToUserName><![CDATA[%s]]></ToUserName>
		<FromUserName><![CDATA[%s]]></FromUserName>
		<CreateTime>%s</CreateTime>
		<MsgType><![CDATA[music]]></MsgType>
		$item_xml
		</xml>";

		$result = sprintf($xml, $object['FromUserName'], $object['ToUserName'], time());
		return $result;
	}
	private function transmitImage($object,$imgurl,$imgname)
	{
	    $imgid = $this->getMediaid($imgurl,'image',$imgname);
		$item="<Image><MediaId><![CDATA[%s]]></MediaId></Image>";
		$item_xml=sprintf($item,$imgid);
		$xml="<xml>
		<ToUserName><![CDATA[%s]]></ToUserName>
		<FromUserName><![CDATA[%s]]></FromUserName>
		<CreateTime>%s</CreateTime>
		<MsgType><![CDATA[image]]></MsgType>
		$item_xml
		</xml>";
		$result = sprintf($xml, $object['FromUserName'], $object['ToUserName'], time());
		return $result;
	}

	private function transmitVideo($object,$videoarr)
	{
	    $videoarr['MediaId'] = $this->getMediaid($videoarr['videourl'],'video',$videoarr['videoname']);

		$item="<Video><MediaId><![CDATA[%s]]></MediaId>
			<Title><![CDATA[%s]]></Title>
			<Description><![CDATA[%s]]></Description></Video>";
    	$item_xml=sprintf($item,$videoarr['MediaId'],$videoarr['Title'],$videoarr['Description']);
    	$xml="<xml>
    	<ToUserName><![CDATA[%s]]></ToUserName>
    	<FromUserName><![CDATA[%s]]></FromUserName>
    	<CreateTime>%s</CreateTime>
    	<MsgType><![CDATA[video]]></MsgType>
    	$item_xml
    	</xml>";
    	$result = sprintf($xml, $object['FromUserName'], $object['ToUserName'], time());
    	return $result;
	}

	private function transmitVoice($object,$voiceurl,$voicename){
        $voiceid = $this->getMediaid($voiceurl,'voice',$voicename);

        $item="<Voice><MediaId><![CDATA[%s]]></MediaId></Voice>";
        $item_xml=sprintf($item,$voiceid);
        $xml="<xml>
		<ToUserName><![CDATA[%s]]></ToUserName>
		<FromUserName><![CDATA[%s]]></FromUserName>
		<CreateTime>%s</CreateTime>
		<MsgType><![CDATA[voice]]></MsgType>
		$item_xml
		</xml>";
        $result = sprintf($xml, $object['FromUserName'], $object['ToUserName'], time());
        return $result;
    }

	//回复多客服消息
	private function transmitService($object)
	{
		$xml= "<xml>
		<ToUserName><![CDATA[%s]]></ToUserName>
		<FromUserName><![CDATA[%s]]></FromUserName>
		<CreateTime>%s</CreateTime>
		<MsgType><![CDATA[transfer_customer_service]]></MsgType>
		</xml>";
        $result = sprintf($xml, $object['FromUserName'], $object['ToUserName'], time());
        return $result;
	}

	private function transmitArticles($object,$data)
	{
		//导入图文数据
		/*$data=array(array(
				'Title'      => '哇吖·城市探秘 | 上海滩杀人事件',
		'Description'=> '100年前，法租界，预告的杀人案，档案馆，时空调查局（TBI），发迹前的黑帮大佬...是虚拟还是现实？是演绎',
		'PicUrl'     => 'https://mmbiz.qlogo.cn/mmbiz_jpg/Pu3ufsdDcY0O97jNtWW993WKiboPTjqIo9XpvR9kQxg51gH2aA54IhK9DmfX4oqYt1VPtEic47fxtSdFqFmvxxkA/0?wx_fmt=jpeg',
		'url'        => 'http://mp.weixin.qq.com/s?__biz=MzIyNzExNDcxOA==&mid=2656038215&idx=1&sn=d04f5ff0317a8b0d859bcce303a6bb5e&chksm=f3dd66f6c4aaefe0e86aafb6efe2a2c74adebf438b53287132290ac9a86d86f4064a77886e7b#rd'
		));*/
		$articles_count = count($data);
		//生成图文xml
		$item = "<item>
		<Title><![CDATA[%s]]></Title>
		<Description><![CDATA[%s]]></Description>
		<PicUrl><![CDATA[%s]]></PicUrl>
		<Url><![CDATA[%s]]></Url>
		</item>";
		$articles_xml = '';
    	foreach($data as $v){
    		$articles_xml .= sprintf($item,$v['Title'],$v['Description'],$v['PicUrl'],$v['url']);
    	}
    	//生成完整回复xml
		$xml = "<xml>
		<ToUserName><![CDATA[%s]]></ToUserName>
		<FromUserName><![CDATA[%s]]></FromUserName>
		<CreateTime>%s</CreateTime>
		<MsgType><![CDATA[news]]></MsgType>
		<ArticleCount>%d</ArticleCount>";
		$result = sprintf($xml, $object['FromUserName'], $object['ToUserName'], time(),$articles_count);
		$result .= "<Articles>$articles_xml</Articles></xml>";
		return $result;
	}

	private function transmitCustomMsg($data){
	    if (!isset($this->CI->wxinterface)){
            $this->CI->load->library("wxinterface/Wxinterface",array("appid"=>$this->_appid,"appsecret"=>$this->_appsecret,"wxtype"=>$this->_wx_type));
        }
        $this->CI->wxinterface->send_custom_msg($data);
    }
	//获取临时素材（图片、声音、视频、缩率图）media_id
	private function getMediaid($mediaurl,$mediatype,$medianame){
        if (!isset($this->CI->wxinterface)){
            $this->CI->load->library("wxinterface/Wxinterface",array("appid"=>$this->_appid,"appsecret"=>$this->_appsecret,"wxtype"=>$this->_wx_type));
        }
        $res=$this->CI->wxinterface->upload_temp_media($mediaurl,$mediatype,$medianame);
        return $res;
    }
    private function getUserNickName($openid)
    {
        if (!isset($this->CI->wxinterface)){
            $this->CI->load->library("wxinterface/Wxinterface",array("appid"=>$this->_appid,"appsecret"=>$this->_appsecret,"wxtype"=>$this->_wx_type));
        }
        $res=$this->CI->wxinterface->getUserInfo($openid);
        return $res['nickname'];
    }
}